package com.daniel.dianping.interceptor;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.daniel.dianping.dto.UserDTO;
import com.daniel.dianping.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.daniel.dianping.utils.RedisConstants.CACHE_TTL_30;
import static com.daniel.dianping.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * 拦截所有请求，进行redis缓存过期刷新
 *
 * @author GanShaoXi
 * @return com.daniel.dianping.interceptor
 * @date 2022/12/28 15:27
 * @versions 1.0.0
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    
    StringRedisTemplate stringRedisTemplate;
    
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            // 为空，未登录放行
            return true;
        }
        // 2.获取Redis中的用户
        String key = LOGIN_USER_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        
        
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            // 用户不存在放行
            return true;
        }
        // 将Map转为userDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), true);
        
        // 4.保存用户到ThreadLocal
        UserHolder.saveUser(userDTO);
        // 刷新缓存时间
        stringRedisTemplate.expire(key, CACHE_TTL_30, TimeUnit.MINUTES);
        // 5.放行
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserHolder.removeUser();
    }
}
